const path = require('path')
const fs = require('fs')

function copyFolderSync(source, target) {
  if (!fs.existsSync(target)) {
    fs.mkdirSync(target)
  }

  fs.readdirSync(source).forEach((file) => {
    const sourcePath = path.join(source, file)
    const targetPath = path.join(target, file)

    if (fs.lstatSync(sourcePath).isDirectory()) {
      copyFolderSync(sourcePath, targetPath)
    } else {
      fs.copyFileSync(sourcePath, targetPath)
    }
  })
}

async function main() {
  const isExitSrc = fs.existsSync(path.join(__dirname, '../../src'))
  const isUni =
    fs.existsSync(path.join(__dirname, '../../node_modules/@dcloudio')) ||
    fs.existsSync(path.join(__dirname, `../../${isExitSrc ? 'src/' : ''}/pages.json`))
  const isTaro = fs.existsSync(path.join(__dirname, '../../node_modules/@tarojs'))

  // 如果是uni或者taro项目，则执行复制
  if (isUni || isTaro) {
    const isExitSrc = fs.existsSync(path.join(__dirname, '../../src'))
    const sourcePath = path.join(__dirname, '../../node_modules/veplayer-mp-douyin')
    let targetPath = ''
    const isExitTTCom = fs.existsSync(path.join(__dirname, `../../${isExitSrc ? 'src/' : ''}ttcomponents`))
    // 不存在则新建文件夹
    if (!isExitTTCom) {
      const ttPath = fs.mkdirSync(path.join(__dirname, `../../${isExitSrc ? 'src/' : ''}ttcomponents`), {
        recursive: true,
      })
      if (!ttPath) {
        console.warn(`创建ttcomponents失败，请手动复制node_modules/veplayer-mp-douyin到${isExitSrc ? 'src/' : ''}tttcomponents`)
        return
      }
    }
    targetPath = path.join(__dirname, `../../${isExitSrc ? 'src/' : ''}ttcomponents/veplayer-mp-douyin`)
    copyFolderSync(sourcePath, targetPath)
  }
}

try {
  main()
} catch (err) {
  console.warn('复制veplayer-mp-douyin失败，请手动复制node_modules/veplayer-mp-douyin到根目录下的ttcomponents')
}
